package com.sqfw.project.wp.service.impl;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.github.pagehelper.PageInfo;
import com.sqfw.common.constant.HttpStatus;
import com.sqfw.common.exception.base.BaseException;
import com.sqfw.common.utils.SecurityUtils;
import com.sqfw.common.utils.StringUtils;
import com.sqfw.framework.web.page.TableDataInfo;
import com.sqfw.project.system.domain.SysDept;
import com.sqfw.project.system.domain.SysUser;
import com.sqfw.project.system.mapper.SysDeptMapper;
import com.sqfw.project.system.mapper.SysUserMapper;
import com.sqfw.project.utils.UpperItemUtils;
import com.sqfw.project.wp.domain.*;
import com.sqfw.project.wp.mapper.WpHandleLogMapper;
import com.sqfw.project.wp.mapper.WpInfoMapper;
import com.sqfw.project.wp.utils.UpperUtils;
import com.sqfw.project.wpReport.domain.WpHoliday;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sqfw.project.wp.mapper.WpInfoReceiveMapper;
import com.sqfw.project.wp.service.IWpInfoReceiveService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 12345工单表Service业务层处理
 *
 * @author lx
 * @date 2023-07-04
 */
@Service
public class WpInfoReceiveServiceImpl implements IWpInfoReceiveService {
    @Autowired
    private WpInfoReceiveMapper wpInfoReceiveMapper;

    @Autowired
    private WpInfoMapper wpInfoMapper;

    @Autowired
    private WpHandleLogMapper wpHandleLogMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;


    /**
     * 查询12345工单表
     *
     * @param scid 12345工单表主键
     * @return 12345工单表
     */
    @Override
    public WpInfoReceive selectWpInfoReceiveByScid(String scid) {
        WpInfoReceive wpInfoReceive = wpInfoReceiveMapper.selectWpInfoReceiveByScid(scid);
        if (wpInfoReceive == null) {
            throw new BaseException("未查询到该12345工单");
        }

        StringBuffer name = new StringBuffer();

        if (StringUtils.isNotEmpty(wpInfoReceive.getClass1())) {

            wpInfoReceive.setMainNodename(wpInfoReceive.getClass1());
        }
        if (StringUtils.isNotEmpty(wpInfoReceive.getClass2())) {

            name.append(wpInfoReceive.getClass2());
        }
        if (StringUtils.isNotEmpty(wpInfoReceive.getClass3())) {

            name.append("/").append(wpInfoReceive.getClass3());
        }
        if (StringUtils.isNotEmpty(wpInfoReceive.getClass4())) {
            name.append("/").append(wpInfoReceive.getClass4());
        }
        if (StringUtils.isNotEmpty(name)) {
            wpInfoReceive.setChildNodeName(name.toString());
        }
        if (StringUtils.isNotEmpty(wpInfoReceive.getWpid())) {
            WpHandleLog wpHandleLog = new WpHandleLog();
            wpHandleLog.setWpid(wpInfoReceive.getWpid());
            List<WpHandleLog> wpHandleLogs = wpHandleLogMapper.selectWpHandleLogList(wpHandleLog);
            if (!wpHandleLogs.isEmpty()) {
                for (WpHandleLog handleLog : wpHandleLogs) {

                    SysUser user = sysUserMapper.selectUserByCode(handleLog.getOperator());
                    SysDept sysDept = sysDeptMapper.selectDeptById(Long.valueOf(handleLog.getDepartment()));
                    if (sysDept != null) {
                        handleLog.setDepartmentName(sysDept.getDeptName());
                    }
                    if (user != null) {
                        handleLog.setNickName(user.getNickName());
                    }
                }
                wpInfoReceive.setWpHandleLogs(wpHandleLogs);
            }
        }
        return wpInfoReceive;
    }

    /**
     * 查询12345工单表列表
     *
     * @param wpInfoReceive 12345工单表
     * @return 12345工单表
     */
    @Override
    public TableDataInfo selectWpInfoReceiveList(WpInfoReceive wpInfoReceive) {

        //内容分类查询条件
        List<List<String>> classAllFind = wpInfoReceive.getClassAllFind();

        //内容分类查询
        if (StringUtils.isEmpty(classAllFind)) {
            wpInfoReceive.setClassAll(null);
        } else {
            List<String> classAllCon = new ArrayList<>();
            for (List<String> strings : classAllFind) {
                classAllCon.add(strings.get(strings.size() - 1));
            }
            wpInfoReceive.setClassAll(classAllCon);
        }
        //排序相关
        String order = wpInfoReceive.getOrder();
        String prop = wpInfoReceive.getProp();
        if (StringUtils.isEmpty(prop)||"calltime".equals(prop)){
            prop = "starttime";
        }
        String orderBy = UpperItemUtils.upperName(order, prop);
        wpInfoReceive.setOrderBy(orderBy);
        //String rowItem = UpperItemUtils.upperRowItem(prop);
        String s = UpperUtils.upperCharToUnderLine(prop);
        wpInfoReceive.setRowItem(s);

        List<String> wpInfoReceives = wpInfoReceiveMapper.selectWpInfoReceiveListAll(wpInfoReceive);
        List<WpInfoReceive> infoReceives = new ArrayList<>();
        if (wpInfoReceives.size() == 0) {
            return getDataTable(infoReceives, wpInfoReceives);
        }

        for (String id : wpInfoReceives) {
            WpInfoReceive infoReceive = wpInfoReceiveMapper.selectWpInfoReceiveByScid(id);
            StringBuffer name = new StringBuffer();

            if (StringUtils.isNotEmpty(infoReceive.getClass1())) {

                infoReceive.setMainNodename(infoReceive.getClass1());
            }
            if (StringUtils.isNotEmpty(infoReceive.getClass2())) {

                name.append(infoReceive.getClass2());
            }
            if (StringUtils.isNotEmpty(infoReceive.getClass3())) {

                name.append("/").append(infoReceive.getClass3());
            }
            if (StringUtils.isNotEmpty(infoReceive.getClass4())) {
                name.append("/").append(infoReceive.getClass4());
            }
            if (StringUtils.isNotEmpty(name)) {
                infoReceive.setChildNodeName(name.toString());
            }
            Integer countSize = wpInfoMapper.countWpInfoByPhoneno(infoReceive.getPhoneno());
            infoReceive.setPhoneCalls(countSize);

            if (StringUtils.isNotEmpty(infoReceive.getSender())) {
                SysUser sysUser = sysUserMapper.selectUserByCode(infoReceive.getSender());
                infoReceive.setSender(sysUser.getNickName());
            }

            infoReceives.add(infoReceive);
        }
        return getDataTable(infoReceives,wpInfoReceives);
    }

    /**
     * 新增12345工单表
     *
     * @param wpInfoReceive 12345工单表
     * @return 结果
     */
    @Override
    public int insertWpInfoReceive(WpInfoReceive wpInfoReceive) {
        return wpInfoReceiveMapper.insertWpInfoReceive(wpInfoReceive);
    }

    /**
     * 修改12345工单表
     *
     * @param wpInfoReceive 12345工单表
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    @Override
    public int updateWpInfoReceive(WpInfoReceive wpInfoReceive) {
        Date date = new Date();
        //查询12345工单
        WpInfo wpInfo = new WpInfo();
        wpInfo.setWpid(wpInfoReceive.getWpid());
        wpInfo.setCustomerName(wpInfoReceive.getCustomerName());
        wpInfo.setPhoneno(wpInfoReceive.getPhoneno());
        wpInfo.setAddress(wpInfoReceive.getAddress());
        wpInfo.setGender(wpInfoReceive.getGender());
        wpInfo.setDistrict(wpInfoReceive.getDistrict());
        wpInfo.setWpType(wpInfoReceive.getWpType());
        wpInfo.setRelAddress(wpInfoReceive.getRelAddress());
        wpInfo.setRelDistrict(wpInfoReceive.getRelDistrict());
        wpInfo.setRelName(wpInfoReceive.getRelName());
        wpInfo.setRelPhoneno(wpInfoReceive.getRelPhoneno());
        wpInfo.setNote(wpInfoReceive.getSummary());
        wpInfo.setStarttime(wpInfoReceive.getStarttime());
        wpInfo.setUpdatetime(date);
        wpInfo.setSender(wpInfoReceive.getSender());
        wpInfo.setCode(wpInfoReceive.getSender());
        wpInfo.setLastmessage(wpInfoReceive.getLastmessage());
        wpInfo.setState(wpInfoReceive.getState());
        wpInfo.setNextState(wpInfoReceive.getNextState());
        wpInfo.setPriority(wpInfoReceive.getPriority());
        wpInfo.setTimeBoundry(wpInfoReceive.getTimeBoundry());
        wpInfo.setCallnum(wpInfoReceive.getCallnum());
        wpInfo.setScidType(wpInfoReceive.getScidType());
        wpInfo.setTsWpid(wpInfoReceive.getTsWpid());
        wpInfo.setWpSource(wpInfoReceive.getWpSource());
        wpInfo.setSupervision(wpInfoReceive.getSupervision());
        wpInfo.setState("社区接收");
        wpInfo.setNextState("12345暂存处理");
        wpInfo.setMemoryInfo("暂存");
        wpInfo.setTimelimite(10);

        wpInfo.setCalltime(date);


        //代表为督办单
        if ("1".equals(wpInfoReceive.getSupervision())) {
            //在wpinfo表中，isSupervision为0代表督办件。为1代表复核件
            wpInfo.setIsSupervision("0");
        }
        String scid = wpInfoMapper.selectWpInfoSeqScid();
        wpInfo.setScid("SQ" + scid);
        wpInfoMapper.insertWpInfo(wpInfo);

        wpInfoReceive.setUpdatetime(date);
        //代表已分配
        wpInfoReceive.setStatus("1");

        this.insertWpHandleLog(wpInfo);
        return wpInfoReceiveMapper.updateWpInfoReceive(wpInfoReceive);
    }

    @Override
    public int updateWpInfoReceiveList(WpInfoReceive wpInfoReceive) {
        int count = 0;
        for (String scid : wpInfoReceive.getScidList()) {
            WpInfoReceive infoReceive = new WpInfoReceive();
            infoReceive.setScid(scid);
            infoReceive.setStatus(wpInfoReceive.getStatus());
            infoReceive.setUpdatetime(new Date());
            wpInfoReceiveMapper.updateWpInfoReceive(infoReceive);
            count++;
        }
        return count;
    }

    @Override
    public List<WpInfoReceive> export(WpInfoReceive wpInfoReceive) {
        //内容分类查询条件
        List<List<String>> classAllFind = wpInfoReceive.getClassAllFind();

        //内容分类查询
        if (StringUtils.isEmpty(classAllFind)) {
            wpInfoReceive.setClassAll(null);
        } else {
            List<String> classAllCon = new ArrayList<>();
            for (List<String> strings : classAllFind) {
                classAllCon.add(strings.get(strings.size() - 1));
            }
            wpInfoReceive.setClassAll(classAllCon);
        }
        //排序相关
        String order = wpInfoReceive.getOrder();
        String prop = wpInfoReceive.getProp();
        if (StringUtils.isEmpty(prop)||"calltime".equals(prop)){
            prop = "starttime";
        }
        String orderBy = UpperItemUtils.upperName(order, prop);
        wpInfoReceive.setOrderBy(orderBy);
        //String rowItem = UpperItemUtils.upperRowItem(prop);
        String s = UpperUtils.upperCharToUnderLine(prop);
        wpInfoReceive.setRowItem(s);

        List<String> wpInfoReceives = wpInfoReceiveMapper.selectWpInfoReceiveListAll(wpInfoReceive);
        List<WpInfoReceive> infoReceives = new ArrayList<>();

        for (String id : wpInfoReceives) {
            WpInfoReceive infoReceive = wpInfoReceiveMapper.selectWpInfoReceiveByScid(id);
            StringBuffer name = new StringBuffer();

            if (StringUtils.isNotEmpty(infoReceive.getClass1())) {

                infoReceive.setMainNodename(infoReceive.getClass1());
            }
            if (StringUtils.isNotEmpty(infoReceive.getClass2())) {

                name.append(infoReceive.getClass2());
            }
            if (StringUtils.isNotEmpty(infoReceive.getClass3())) {

                name.append("/").append(infoReceive.getClass3());
            }
            if (StringUtils.isNotEmpty(infoReceive.getClass4())) {
                name.append("/").append(infoReceive.getClass4());
            }
            if (StringUtils.isNotEmpty(name)) {
                infoReceive.setChildNodeName(name.toString());
            }
            Integer countSize = wpInfoMapper.countWpInfoByPhoneno(infoReceive.getPhoneno());
            infoReceive.setPhoneCalls(countSize);

            if (StringUtils.isNotEmpty(infoReceive.getSender())) {
                SysUser sysUser = sysUserMapper.selectUserByCode(infoReceive.getSender());
                infoReceive.setSender(sysUser.getNickName());
            }

            infoReceives.add(infoReceive);
        }
        return infoReceives;
    }

    //新增轨迹表数据
    private void insertWpHandleLog(WpInfo wpInfo) {
        Date date = new Date();
        //添加完成后，需要将在主轨迹表添加轨迹数据
        WpHandleLog wpHandleLog = new WpHandleLog();
        //登录人员信息
        SysUser user = SecurityUtils.getLoginUser().getUser();
        wpHandleLog.setWpid(wpInfo.getWpid());
        wpHandleLog.setOperator(user.getCode());
        wpHandleLog.setMessage(wpInfo.getLastmessage());
        wpHandleLog.setLastState(wpInfo.getState());
        wpHandleLog.setNextState(wpInfo.getNextState());
        wpHandleLog.setSummary(wpInfo.getSummary());
        //部门id
        wpHandleLog.setDepartment(user.getDeptId().toString());

        wpHandleLog.setUpdateTime(date);
        String processId = wpHandleLogMapper.getWpHandleLogId();
        wpHandleLog.setProcessId("SQ" + processId);
        wpHandleLogMapper.insertWpHandleLog(wpHandleLog);
    }
    protected TableDataInfo getDataTable(List<?> list, List<?> total) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(total).getTotal());
        return rspData;
    }
}
